<?php
namespace app\farm\controller;
use app\ApiRest;

use app\farm\model\Address;
use app\farm\model\BalanceOrder;
use app\farm\model\BalanceWater;
use app\farm\model\Banner;
use app\farm\model\Breed;
use app\farm\model\BreedOrder;
use app\farm\model\BreedOrderGoods;
use app\farm\model\Car;
use app\farm\model\Claim;
use app\farm\model\ClaimCollage;
use app\farm\model\ClaimOrder;
use app\farm\model\ClaimText;
use app\farm\model\CollageJoin;
use app\farm\model\CollageStart;
use app\farm\model\Config;
use app\farm\model\Coupon;
use app\farm\model\CouponRecord;
use app\farm\model\Evaluate;
use app\farm\model\FinanceWater;
use app\farm\model\LandCate;
use app\farm\model\Farmer;

use app\farm\model\LandOrder;
use app\farm\model\LandSourceText;
use app\farm\model\Machine;
use app\farm\model\OrderAddress;
use app\farm\model\SendConfig;
use app\farm\model\SendOrder;
use app\farm\model\Source;
use app\massage\controller\IndexWxPay;
use app\farm\model\User;
use app\shop\model\FreightTemplate;
use longbingcore\wxcore\PayModel;
use think\App;
use think\facade\Db;
use think\Request;


class IndexClaim extends ApiRest
{

    protected $model;

    protected $app;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->app = $app;

        $this->model = new Claim();

        autoCancelOrder($this->_uniacid);

        $collage_model = new CollageStart();

        $collage_model->initAtv($this->payConfig());

        $push_data = array(

            'action' => 'collageFailCancelOrder',

            'event'  => 'collageFailCancelOrder',

            'pay_config' => $this->payConfig()

        );
        publisher(json_encode($push_data, true));
    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-06 14:03
     * @功能说明:认养轮播图
     */
    public function claimBanner(){

        $input = $this->_param;

        $banner_model = new Banner();

        $dis = [

            'type'    => $input['type'],

            'status'  => 1,

            'uniacid' => $this->_uniacid
        ];

        $data = $banner_model->where($dis)->order('top desc,id desc')->select()->toArray();

        return $this->success($data);

    }





    /**
     * @author chenniang
     * @DataTime: 2021-12-14 17:42
     * @功能说明:认养分类列表
     */
    public function claimCateList(){

        $input = $this->_param;

        $cate_model = new LandCate();

        $dis = [

            'type'    => $input['type'],

            'uniacid' => $this->_uniacid,

            'status'  => 1,

        ];

        $data = $cate_model->where($dis)->order('top desc,id desc')->select()->toArray();

        return $this->success($data);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-12-14 17:53
     * @功能说明:认养列表
     */
    public function claimList(){

        $input = $this->_param;

        $farmer_model = new Farmer();

        $claim_order  = new ClaimOrder();

        $user_model   = new User();

        $input['sort'] = !empty($input['sort'])?$input['sort']:1;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.status','=',1];

        $dis[] = ['a.end_time','>',time()];

        if(!empty($input['cate_id'])){

            $dis[] = ['b.cate_id','=',$input['cate_id']];

            $dis[] = ['b.type','=',3];
        }

        if(!empty($input['title'])){

            $dis[] = ['a.title','like','%'.$input['title'].'%'];

        }

        if(!empty($input['farmer_id'])){

            $dis[] = ['a.farmer_id','=',$input['farmer_id']];

        }else{

            $id = $farmer_model->farmerId($this->_uniacid);

            $dis[] = ['a.farmer_id','in',$id];

        }

        $lat = !empty($input['lat'])?$input['lat']:0;

        $lng = !empty($input['lng'])?$input['lng']:0;

        $alh = '(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*('.$lng.'- `lng`)/360),2)+COS(PI()*33.07078170776367/180)* COS('.$lat.' * PI()/180)*POW(SIN(PI()*('.$lat.'- lat)/360),2))))*1000 as distance';

        $data = $this->model->indexDataListV2($dis,$alh,$input['sort']);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['count']['user_count'] = $claim_order->where(['claim_id'=>$v['id']])->where('pay_type','>',1)->group('user_id')->count();

                $order_user_id = $claim_order->where(['claim_id'=>$v['id']])->where('pay_type','>',1)->group('user_id')->order('id desc')->limit(3)->column('user_id');

                $v['count']['user_list'] = $user_model->where('id','in',$order_user_id)->field('avatarUrl')->select()->toArray();

                $v['farmer_info'] = $farmer_model->dataInfo(['id'=>$v['farmer_id']],'title,cover');

                $v['start_time']  = date('Y-m-d',$v['start_time']);

                $v['end_time']    = date('Y-m-d',$v['end_time']);

            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-16 10:34
     * @功能说明:认养详情
     */
    public function claimInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        $farmer_model = new Farmer();

        $data['farmer_info'] = $farmer_model->dataInfo(['id'=>$data['farmer_id']]);

        $claim_text_model = new ClaimText();

        $data['process'] = $claim_text_model->where(['claim_id'=>$data['id']])->select()->toArray();

        $mac_model = new Machine();
        //仪器详情
        $data['machine_info'] = $mac_model->getDataInfo($data['id'],2);

        $collage_model = new CollageStart();
        //拼团列表
        $data['collage_list'] = $collage_model->claimCollageLimit($data['id'],3,$this->getUserId());
        //用户正在发起的拼团
        $data['user_start_collage'] = $collage_model->userCollageIngData($this->getUserId(),$data['id']);

        $collage_model = new ClaimCollage();
        //商品拼团活动
        $data['collage_data'] = $collage_model->getAtvInfoIng($data['id'],$this->getUserId());

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-16 17:51
     * @功能说明:认养拼团列表
     */
    public function claimCollageList(){

        $input = $this->_param;

        $collage_model = new CollageStart();

        $dis[] = ['end_time','>',time()];

        $dis[] = ['status','=',1];

        $dis[] = ['claim_id','=',$input['claim_id']];
        //拼团
        $data= $collage_model->claimCollageList($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-16 17:53
     * @功能说明:认养拼团详情
     */
    public function claimCollageInfo(){

        $input = $this->_param;

        $collage_model = new CollageStart();

        $join_model = new CollageJoin();

        $order_model = new ClaimOrder();

        $data = $collage_model->dataInfo(['id'=>$input['id']]);

        if(empty($data)){

            $this->errorMsg('拼团未找到');
        }

        $data['user_list'] = $join_model->collageUserAvatar($input['id'],5);

        $claim = $this->model->dataInfo(['id'=>$data['claim_id']]);

        $data['claim_title'] = $claim['title'];

        $data['claim_cover'] = $claim['cover'];

        $data['claim_price'] = $claim['price'];

        $data['can_start'] = $collage_model->startAtvCheck($this->getUserId(),$data['atv_id']);
        //是否还能发起该活动其他的拼团
        $data['can_start'] = !empty($data['can_start']['code'])?0:1;
        //是否能参与拼团
        $data['can_join'] = $join_model->collageCanJoin($this->getUserId(),$data['id']);

        return $this->success($data);

    }







    /**
     * @author chenniang
     * @DataTime: 2022-01-10 10:05
     * @功能说明:下单页信息
     */
    public function claimPayOrderInfo(){

        $input = $this->_param;

        $order_model = new ClaimOrder();

        $data = $order_model->payOrderInfo($input);

        if(!empty($data['code'])){

            $this->errorMsg($data['msg']);
        }

        $farmer_model = new Farmer();

        $arr['farmer_info'] = $farmer_model->dataInfo(['id'=>$data['farmer_id']]);

        $arr['claim_info']  = $data;

        $address_model  = new Address();

        if(!empty($input['address_id'])){

            $arr['address'] = $address_model->dataInfo(['id'=>$input['address_id']]);

        }else{

            $arr['address'] = $address_model->dataInfo(['user_id'=>$this->getUserId(),'status'=>1]);

        }

        $coupon_modle  = new Coupon();

        $coupon_record_model  = new CouponRecord();
        //可用优惠券数量
        $canUseCoupon = $coupon_modle->canUseCoupon($this->getUserId(),$data['pay_price'],3);

        $arr['canUseCoupon'] = $coupon_record_model->where('id','in',$canUseCoupon)->sum('num');

        $arr['pay_price'] = $data['pay_price'];

        $arr['coupon_discount'] = $data['coupon_discount'];

        $arr['coupon_id'] = $data['coupon_id'];

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-16 10:57
     * @功能说明:认养下单
     */
    public function claimPayOrder(){

        $input = $this->_input;

        $order_model = new ClaimOrder();

        $data = $order_model->payOrderInfo($input,1);

        if(!empty($data['code'])){

            $this->errorMsg($data['msg']);
        }

        $address_model = new OrderAddress();

        $order_insert = [

            'uniacid'      => $this->_uniacid,

            'pay_type'     => 1,

            'order_code'   => orderCode(),

            'claim_code'   => short_orderCode(),

            'user_id'      => $this->getUserId(),

            'pay_price'    => round($data['pay_price'],2),

            'get_integral' => round($data['pay_price'],2),

            'init_price'   => round($data['init_price'],2),

            'balance'      => $input['pay_model']==2?round($data['pay_price'],2):0,

            'goods_id'     => $data['id'],

            'goods_name'   => $data['title'],

            'goods_cover'  => $data['cover'],

            'goods_price'  => $data['price'],

            'breed'        => $data['breed'],

            'cycle'        => $data['cycle'],

            'start_time'   => $data['start_time'],

            'end_time'     => $data['end_time'],

            'harvest_text' => $data['harvest_text'],

            'harvest_cover'=> $data['harvest_cover'],

            'name'         => $input['claim_name'],

            'send_type'    => $input['send_type'],

            'num'          => $input['num'],

            'text'         => $input['text'],

            'claim_id'     => $data['id'],

            'farmer_id'    => $data['farmer_id'],

            'source_id'    => $data['source_id'],

            'send_cycle'   => $data['send_cycle'],

            'send_times'   => $data['send_times'],

            'unit'         => $data['unit'],
             //
            'over_time'    => time()+$this->_config['over_time']*60,

            'pay_model'    => $input['pay_model'],

            'coupon_id'    => $data['coupon_id'],

            'discount_price'=> $data['coupon_discount'],

            'is_collage'    => !empty($input['collage_start_id'])||!empty($input['collage_join_id'])?1:0,

        ];

        Db::startTrans();

        $order_model = new ClaimOrder();

        $res = $order_model->dataAdd($order_insert);

        if($res==0){

            Db::rollback();

            $this->errorMsg('下单失败1');

        }

        $order_id = $order_model->getLastInsID();

        $order_insert['id'] = $order_id;

        $input['uniacid'] = $this->_uniacid;

        $res = $address_model->orderAddressAdd($input['address_id'],$order_id,$input['send_type'],2,$input);

        if($res==0){

            Db::rollback();

            $this->errorMsg('下单失败2');

        }
        //加销量减库存
        $update = [

            'stock'    => $data['stock'] -$input['num'],

            'sale_num' => $data['sale_num']+$input['num'],

            'lock'     => $data['lock']+1

        ];

        $res = $this->model->where(['id'=>$data['id'],'lock'=>$data['lock']])->update($update);

        if($res==0){

            Db::rollback();

            $this->errorMsg('下单失败3');

        }
        //使用优惠券
        if(!empty($data['coupon_id'])){

            $coupon_record_model = new CouponRecord();

            $coupon_record_model->couponUse($data['coupon_id'],$order_id,3);

        }

        $is_start = 0;
        //发起拼团
        if(!empty($data['collage_start_data'])){

            $start_model = new CollageStart();

            $data['collage_join_data'] = $start_model->startCollage($order_insert,$data['collage_start_data']);

            if(!empty($data['collage_join_data']['code'])){

                Db::rollback();

                $this->errorMsg($data['collage_join_data']['msg']);
            }

            $is_start = 1;

        }
        //参与拼团
        if(!empty($data['collage_join_data'])){

            $join_model = new CollageJoin();

            $res = $join_model->joinCollage($order_insert,$data['collage_join_data'],$is_start);

            if(!empty($res['code'])){

                Db::rollback();

                $this->errorMsg($res['msg']);
            }

        }

        Db::commit();
        //如果是0元
        if($order_insert['pay_price']<=0){

            $order_model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);
        }
        //余额支付
        if($input['pay_model']==2){

            $user_model = new \app\farm\model\User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_insert['pay_price']){

                $this->errorMsg('余额不足');
            }

            $order_model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);

        }elseif ($input['pay_model']==3){

            $pay_model = new PayModel($this->payConfig());

            $jsApiParameters = $pay_model->aliPay($order_insert['order_code'],$order_insert['pay_price'],'认养商品');

            $arr['pay_list']= $jsApiParameters;

            $arr['order_code']= $order_insert['order_code'];


        }else{
            //微信支付
            $pay_controller = new \app\shop\controller\IndexWxPay($this->app);
            //支付
            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"认养订单",['type' => 'Claim' , 'out_trade_no' => $order_insert['order_code']],$order_insert['pay_price']);

            $arr['pay_list']= $jsApiParameters;

        }

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-20 10:17
     * @功能说明:认养重新下单
     */
    public function claimRePayOrder(){

        $input = $this->_input;

        $order_model = new ClaimOrder();

        $order_insert = $order_model->dataInfo(['id'=>$input['id']]);

        if($order_insert['pay_type']!=1){

            $this->errorMsg('订单状态错误');
        }
        //余额支付
        if($order_insert['pay_model']==2){

            $user_model = new \app\farm\model\User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_insert['pay_price']){

                $this->errorMsg('余额不足');
            }

            $order_model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);

        }elseif ($order_insert['pay_model']==3){

            $pay_model = new PayModel($this->payConfig());

            $jsApiParameters  = $pay_model->aliPay($order_insert['order_code'],$order_insert['pay_price'],'认养商品');

            $arr['pay_list']  = $jsApiParameters;

            $arr['order_code']= $order_insert['order_code'];

        }else{

            //微信支付
            $pay_controller = new \app\shop\controller\IndexWxPay($this->app);
            //支付
            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"认养订单",['type' => 'Claim' , 'out_trade_no' => $order_insert['order_code']],$order_insert['pay_price']);

            $arr['pay_list']= $jsApiParameters;
        }

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-28 11:26
     * @功能说明:用户下单列表
     */
    public function orderList(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['user_id','=',$this->getUserId()];

        if(!empty($input['pay_type'])){

            $dis[] = ['pay_type','=',$input['pay_type']];

        }

        if(!empty($input['order_code'])){

            $dis[] = ['order_code','like','%'.$input['order_code'].'%'];

        }

        $order_model  = new ClaimOrder();

        $farmer_model = new Farmer();

        $eva_model    = new Evaluate();

        $data = $order_model->dataList($dis);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['farmer_info'] = $farmer_model->dataInfo(['id'=>$v['farmer_id']],'title');

                $dis = [

                    'user_id' => $this->getUserId(),

                    'order_id'=> $v['id'],

                    'type'    => 1
                ];

                $have_eva = $eva_model->where($dis)->where('status','>',-1)->find();
                //是否已经评价
                $v['have_eva'] = !empty($have_eva)?1:0;

            }
        }

        $arr = [2=>'claim_count',3=>'send_count'];

        foreach ($arr as $key => $value){

            $where = [

                'user_id' => $this->getUserId(),

                'pay_type'=> $key
            ];

            $data['count'][$value] = $order_model->where($where)->count();

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-28 11:52
     * @功能说明:用户下单详情
     */
    public function orderInfo(){

        $input = $this->_param;

        $farmer_model = new Farmer();

        $source_model = new Source();

        $dis = [

            'id' => $input['id']
        ];

        $order_model = new ClaimOrder();

        $data = $order_model->dataInfo($dis);

        $data['over_time'] -= time();

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

        $data['pay_time']    = $data['pay_time']>0?date('Y-m-d H:i:s',$data['pay_time']):0;

        $data['cancel_time'] = $data['cancel_time']>0?date('Y-m-d H:i:s',$data['cancel_time']):0;

        $data['time_text']   = date('Y-m-d',$data['start_time']).'~'.date('Y-m-d',$data['end_time']);
        //农场信息
        $data['farmer_info'] = $farmer_model->dataInfo(['id'=>$data['farmer_id']]);
        //溯源信息
        $data['source'] = $source_model->dataInfo(['id'=>$data['source_id']]);
        //是否可以配送
        $data['can_send'] = $data['pay_type']>1&&$data['end_time']<time()?1:0;

        $eva_model = new Evaluate();

        $dis = [

            'user_id' => $this->getUserId(),

            'order_id'=> $input['id'],

            'type'    => 1
        ];

        $have_eva = $eva_model->where($dis)->where('status','>',-1)->find();
        //是否已经评价
        $data['have_eva'] = !empty($have_eva)?1:0;

        $address_order_model  = new OrderAddress();

        $address_model        = new Address();

        $data['address_info'] = $address_order_model->dataInfo(['order_id'=>$input['id'],'type'=>2]);

        if(!empty($data['address_info']['address_id'])){

            $data['address_info'] = $address_model->dataInfo(['id'=>$data['address_info']['address_id']]);

        }

        $mac_model = new Machine();
        //仪器详情
        $data['machine_info'] = $mac_model->getDataInfo($data['claim_id'],2);

        $send_tmpl_id = $this->model->where(['id'=>$data['claim_id']])->value('send_tmpl_id');

        $freightTemplate_model = new FreightTemplate();
        //配送运费模版
        $data['send_tmpl'] = $freightTemplate_model->dataInfo(['id'=>$send_tmpl_id]);

        if($data['is_collage']==1){

            $collage_model = new CollageJoin();

            $collage_info  = $collage_model->dataInfo(['order_id'=>$input['id']]);

            if(!empty($collage_info)){

                $data['collage_status'] = $collage_info['status'];

                $data['collage_discount_price'] = $data['init_price']-$collage_info['price'];

                $data['collage_discount_price'] = $data['collage_discount_price']>0?$data['collage_discount_price']:0;


            }

        }

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-10 13:42
     * @功能说明:
     */
    public function cancelOrder(){

        $input = $this->_input;

        $order_model = new ClaimOrder();

        $dis = [

            'id' => $input['id']
        ];

        $order = $order_model->dataInfo($dis);

        if($order['pay_type']!=1){

            $this->errorMsg('订单状态错误');
        }

        $res = $order_model->cancelOrder($order);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-12-29 10:29
     * @功能说明:养殖管理
     */
    public function breedList(){

        $input = $this->_param;

        $breed_model = new Breed();

        $car_model   = new Car();

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.status','=',1];

        $dis[] = ['b.type','=',5];

        if(!empty($input['title'])){

            $dis[] = ['a.title','like','%'.$input['title'].'%'];
        }

        $dis[] = ['b.store_id','=',$input['farmer_id']];

        $data = $breed_model->indexDataList($dis);

        $dis = [

            'user_id'=>$this->getUserId(),

            'type'   =>1,

            'status' =>1,

            'farmer_id' => $input['farmer_id']
        ];

        $car = $breed_model->getCarList($this->getUserId(),$input['farmer_id']);

        $data['count'] = $car['goods_num'];

        $data['total_price'] = $car['price'];

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $dis['goods_id'] = $v['id'];

                $v['car_num'] = $car_model->where($dis)->sum('goods_num');

                $v['car_id'] = $car_model->where($dis)->value('id');

            }

        }

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-29 17:02
     * @功能说明:养殖订单
     */
    public function breedOrder(){

        $input = $this->_input;

        $breed_model = new Breed();

        $order_model = new BreedOrder();

        $claim_order_model = new ClaimOrder();

        $framer_model= new Farmer();

        $claim_order = $claim_order_model->dataInfo(['id'=>$input['claim_order_id']]);

        $pay_order   = $breed_model->getCarList($this->getUserId(),$claim_order['farmer_id']);

        $farmer = $framer_model->dataInfo(['id'=>$claim_order['farmer_id'],'status'=>2]);

        if(empty($farmer)){

            $this->errorMsg('该农场主已被取消农场身份，无法下单');
        }

        $order_insert = [

            'uniacid'        => $this->_uniacid,

            'order_code'     => orderCode(),

            'user_id'        => $this->getUserId(),

            'claim_order_id' => $input['claim_order_id'],

            'farmer_id'      => $claim_order['farmer_id'],

            'pay_price'      => $pay_order['price'],

            'get_integral'   => $pay_order['price'],

            'text'           => $input['text'],

            'pay_model'      => $input['pay_model'],

            'balance'        => $input['pay_model']==2?round($pay_order['price'],2):0,
        ];

        Db::startTrans();

        $res = $order_model->dataAdd($order_insert);

        if($res==0){

            Db::rollback();

            $this->errorMsg('下单失败');

        }

        $order_id = $order_model->getLastInsID();

        $order_goods_model = new BreedOrderGoods();

        $res = $order_goods_model->orderAdd($pay_order['car_list'],$order_id);

        if($res==0){

            Db::rollback();

            $this->errorMsg('下单失败');

        }
        //清空购物车
        $car_model = new Car();

        $dis = [

            'farmer_id' => $claim_order['farmer_id'],

            'user_id'   => $this->getUserId(),

            'type'      => 1,

            'status'    => 1
        ];

        $car_model->where($dis)->delete();

        Db::commit();
        //如果是0元
        if($order_insert['pay_price']<=0){

            $order_model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);
        }
        //余额支付
        if($input['pay_model']==2){

            $user_model = new \app\farm\model\User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_insert['pay_price']){

                $this->errorMsg('余额不足');
            }

            $order_model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);

        }elseif ($input['pay_model']==3){

            $pay_model = new PayModel($this->payConfig());

            $jsApiParameters = $pay_model->aliPay($order_insert['order_code'],$order_insert['pay_price'],'养殖商品');

            $arr['pay_list']= $jsApiParameters;

            $arr['order_code']= $order_insert['order_code'];

        }else{
            //微信支付
            $pay_controller = new \app\shop\controller\IndexWxPay($this->app);
            //支付
            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"养殖订单",['type' => 'Breed' , 'out_trade_no' => $order_insert['order_code']],$order_insert['pay_price']);

            $arr['pay_list']= $jsApiParameters;
        }

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-10 15:52
     * @功能说明:养殖订单列表
     */
    public function breedOrderList(){

        $input = $this->_param;

        $dis[] = ['pay_type','>',1];

        $dis[] = ['claim_order_id','=',$input['claim_order_id']];

        $order_model = new BreedOrder();

        $data = $order_model->dataList($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-10 16:07
     * @功能说明:养殖订单详情
     */
    public function breedOrderInfo(){

        $input = $this->_param;

        $dis[] = ['id','=',$input['id']];

        $order_model = new BreedOrder();

        $data = $order_model->dataInfo($dis);

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

        $data['pay_time']    = !empty($data['pay_time'])?date('Y-m-d H:i:s',$data['pay_time']):0;

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-08 17:14
     * @功能说明:配送订单列表
     */
    public function userSendOrderList(){

        $input = $this->_param;

        $send_order_model = new SendOrder();

        $data = $send_order_model->orderSendOrder($input['claim_order_id']);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-08 13:53
     * @功能说明:申请认养订单发货
     */
    public function sendOrderApply(){

        $input = $this->_input;

        $order_model = new ClaimOrder();

        $farmer_model= new Farmer();

        $config_model= new Config();

        $address_model    = new Address();

        $send_order_model = new SendOrder();

        $order = $order_model->dataInfo(['id'=>$input['order_id']]);

        if($order['pay_type']<2){

            $this->errorMsg('订单未支付');

        }
        //已经申请的配送次数
        $send_count = $send_order_model->where(['order_id'=>$input['order_id'],'type'=>1])->where('pay_type','>',1)->count();

        if($send_count>=$order['send_times']){

            $this->errorMsg('已经到达配送次数上线');

        }

        $times = $send_order_model->where(['order_id'=>$input['order_id'],'type'=>1])->where('pay_time','>',0)->count();

        $farmer= $farmer_model->dataInfo(['id'=>$order['farmer_id'],'status'=>2]);

        if(empty($farmer)){

            $this->errorMsg('农场主未找到');
        }


        $send_price = $distance = 0;
        //快递
        if($input['send_type']==2){

            $address = $address_model->dataInfo(['id'=>$input['address_id']]);

            if(empty($address)){

                $this->errorMsg('地址信息未找到');

            }

            $cliam_info = $this->model->dataInfo(['id'=>$order['claim_id']]);

            if(empty($cliam_info)){

                $this->errorMsg('认养信息被删除');

            }

            $goods_info = [

                'send_tmpl_id' => $cliam_info['send_tmpl_id'],

                'goods_num'    => $input['send_num'],

                'total_weight' => $input['send_num'],
            ];

            $send_data = $config_model->getGoodsSendPrice($input['address_id'],$goods_info,2,2);

            if(!empty($send_data['code'])){

                $this->errorMsg($send_data['msg']);
            }

            $send_price = $send_data['price'];

            $send_tmpl_type = $send_data['type'];

        }else{

            $address['user_name'] = $input['user_name'];

            $address['mobile']    = $input['mobile'];

        }

        $order_insert = [

            'uniacid'    => $this->_uniacid,

            'order_id'   => $input['order_id'],

            'pay_model'  => $input['pay_model'],

            'user_id'    => $order['user_id'],

            'farmer_id'  => $order['farmer_id'],

            'pay_price'  => $send_price,

            'get_integral' => $send_price,

            'order_code' => orderCode(),

            'text'       => $input['text'],
            //
            'over_time'  => time()+$this->_config['over_time']*60,

            'type'       => 1,

            'start_time' => $input['start_time'],

            'end_time'   => $input['end_time'],

            'times'      => $times+1,

            'send_type'  => $input['send_type'],

            'address'    => $input['send_type']==2?$address['address'].$address['address_info']:'',

            'user_name'  => $address['user_name'],

            'mobile'     => $address['mobile'],

            'lng'        => $input['send_type']==2?$address['lng']:'',

            'lat'        => $input['send_type']==2?$address['lat']:'',

            'balance'    => $input['pay_model']==2?$send_price:0,

            'goods_num'  => isset($send_tmpl_type)&&$send_tmpl_type==1?$input['send_num']:0,

            'weight'     => isset($send_tmpl_type)&&$send_tmpl_type==2?$input['send_num']:0,

        ];

        $res = $send_order_model->dataAdd($order_insert);

        if($res==0){

            $this->errorMsg('申请配送失败');
        }
        //如果是0元
        if($order_insert['pay_price']<=0){

            $send_order_model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);
        }
        //余额支付
        if($input['pay_model']==2){

            $user_model = new \app\farm\model\User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_insert['pay_price']){

                $this->errorMsg('余额不足');
            }

            $send_order_model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);

        }elseif ($input['pay_model']==3){

            $pay_model = new PayModel($this->payConfig());

            $jsApiParameters = $pay_model->aliPay($order_insert['order_code'],$order_insert['pay_price'],'配送订单');

            $arr['pay_list']= $jsApiParameters;

            $arr['order_code']= $order_insert['order_code'];

        }else{
            //微信支付
            $pay_controller = new \app\shop\controller\IndexWxPay($this->app);
            //支付
            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"认养配送订单",['type' => 'ClaimSend' , 'out_trade_no' => $order_insert['order_code']],$order_insert['pay_price']);

            $arr['pay_list']= $jsApiParameters;

        }

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-08 15:23
     * @功能说明:配送订单下单详情
     */
    public function sendOrderPayInfo(){

        $input  = $this->_param;

        $order_model = new ClaimOrder();

        $farmer_model= new Farmer();

        $config_model= new Config();

        $address_model = new Address();

        $order = $order_model->dataInfo(['id'=>$input['order_id']]);

        $farmer= $farmer_model->dataInfo(['id'=>$order['farmer_id']]);

        if(empty($farmer)){

            $this->errorMsg('农场主未找到');
        }

        $address = $address_model->dataInfo(['id'=>$input['address_id']]);

        if(empty($address)){

            $this->errorMsg('地址信息未找到');

        }
        $cliam_info = $this->model->dataInfo(['id'=>$order['claim_id']]);

        $freightTemplate_model = new FreightTemplate();

        $data['send_tmpl'] = $freightTemplate_model->dataInfo(['id'=>$cliam_info['send_tmpl_id']]);

        if(!empty($input['send_num'])){

            $goods_info = [

                'send_tmpl_id' => $cliam_info['send_tmpl_id'],

                'goods_num'    => $input['send_num'],

                'total_weight' => $input['send_num'],
            ];

            $data['send_price'] = $config_model->getGoodsSendPrice($input['address_id'],$goods_info,2);

            if(!empty($data['send_price']['code'])){

                $this->errorMsg($data['send_price']['msg']);
            }
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-08 15:10
     * @功能说明:获取配送时间段
     */
    public function sendTime(){

        $config_model = new Config();

        $send_config  = new SendConfig();

        $config = $config_model->dataInfo(['uniacid'=>$this->_uniacid]);

        $config['app_day'] = $config['app_day']>30?30:$config['app_day'];

        $i = 0;
        //预约的每一天
        while ($i<$config['app_day']){

            $time = time()+86400*$i;

            $arr['date'] = date('Y-m-d',$time);

            $arr['week'] = changeWeek(date('w',$time));

            $data['date'][] = $arr;

            $i++;
        }
        //每天时间段
        $data['time'] = $send_config->where(['uniacid'=>$this->_uniacid,'status'=>1])->select()->toArray();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-08 17:57
     * @功能说明:配送订单退款
     */
    public function sendOrderRefund(){

        $input = $this->_input;

        $send_order_model = new SendOrder();

        $send_order = $send_order_model->dataInfo(['id'=>$input['id']]);

        if(empty($send_order)){

            $this->errorMsg('订单未找到');
        }

        if($send_order['pay_type']!=2){

            $this->errorMsg('订单状态错误');
        }

        Db::startTrans();

        $res = $send_order_model->refundCash($send_order,$this->payConfig($this->_uniacid));

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        $send_order_model->dataUpdate(['id'=>$send_order['id']],['refund_time'=>time(),'pay_type'=>-1,'refund'=>1]);
        //增加财务流水
        $fin_water_model = new FinanceWater();

        $res = $fin_water_model->addWater($input['id'],11,1,1);

        if($res==0){

            Db::rollback();

            $this->errorMsg('退款失败1');
        }

        $res = $fin_water_model->dataUpdate(['order_id'=>$send_order['id'],'type'=>10],['cash_status'=>1]);

        if($res==0){

            Db::rollback();

            $this->errorMsg('退款失败3');
        }
        Db::commit();

        return $this->success(true);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-09 10:24
     * @功能说明:配送订单收货
     */
    public function sendOrderReceiving(){

        $input = $this->_input;

        $send_order_model = new SendOrder();

        $send_order = $send_order_model->dataInfo(['id'=>$input['id']]);

        if(empty($send_order)){

            $this->errorMsg('订单未找到');
        }

        if($send_order['pay_type']!=3){

            $this->errorMsg('订单状态错误');
        }

        $res = $send_order_model->sendOrderReceiving($send_order);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success(true);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-09 14:00
     * @功能说明:配送订单详情
     */
    public function sendOrderInfo(){

        $input = $this->_param;

        $send_order_model = new SendOrder();

        $claim_order_model= new ClaimOrder();

        $send_order = $send_order_model->dataInfo(['id'=>$input['id']]);

        $send_order['create_time']    = date('Y-m-d H:i:s',$send_order['create_time']);

        $send_order['time_text']      = date('Y-m-d H:i',$send_order['start_time']).'~'.date('H:i',$send_order['end_time']);

        $send_order['pay_time']       = $send_order['pay_time']>0?date('Y-m-d H:i:s',$send_order['pay_time']):0;

        $send_order['send_time']      = $send_order['send_time']>0?date('Y-m-d H:i:s',$send_order['send_time']):0;

        $send_order['receiving_time'] = $send_order['receiving_time']>0?date('Y-m-d H:i:s',$send_order['receiving_time']):0;

        $send_order['refund_time']    = $send_order['refund_time']>0?date('Y-m-d H:i:s',$send_order['refund_time']):0;

        $send_order['claim_order']= $claim_order_model->dataInfo(['id'=>$send_order['order_id']]);

        return $this->success($send_order);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-10 00:40
     * @功能说明:可用的优惠券列表
     */
    public function couponList(){

        $input = $this->_param;

        $coupon_model = new Coupon();

        $coupon_record_model = new CouponRecord();

        $order_model    = new ClaimOrder();

        $order_info = $order_model->payOrderInfo($input);

        $coupon_id = $coupon_model->canUseCoupon($this->getUserId(),$order_info['pay_price'],3);

        $data = $coupon_record_model->where('id','in',$coupon_id)->order('id desc')->paginate(10)->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['start_time'] = date('Y.m.d H:i',$v['start_time']).' - '.date('Y.m.d H:i',$v['end_time']);

            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-16 15:15
     * @功能说明:用户认养拼团
     */
    public function userCollageLimit(){

        $input = $this->_param;

        $collage_model = new CollageJoin();

        $dis[] = ['a.user_id','=',$this->getUserId()];

        $dis[] = ['a.status','=',1];

        $data = $collage_model->userCollageLimit($dis);

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-16 15:15
     * @功能说明:用户认养拼团列表
     */
    public function userCollageList(){

        $input = $this->_param;

        $collage_model = new CollageJoin();

        $dis[] = ['a.user_id','=',$this->getUserId()];

        if(!empty($input['status'])&&$input['status']==2){

            $dis[] = ['a.status','=',$input['status']];

        }else{

            $dis[] = ['a.status','in',[1,3]];
        }

        $data = $collage_model->userCollagePage($dis);

        $data['total_num'] = $collage_model->userCollageCount($this->getUserId());

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-16 16:12
     * @功能说明:拼团商品列表
     */
    public function collageList(){

        $collage_model = new ClaimCollage();

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.status','=',1];

        $dis[] = ['a.start_time','<',time()];

        $dis[] = ['a.end_time','>',time()];

        if(!empty($input['title'])){

            $dis[] = ['a.title','like','%'.$input['title'].'%'];
        }

        if(!empty($input['goods_name'])){

            $dis[] = ['b.title','like','%'.$input['goods_name'].'%'];
        }

        $data = $collage_model->adminDataList($dis);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['time_text'] = lbGetDatesss($v['end_time']);

            }

        }

        return $this->success($data);
    }






}
